package xyz.zchao.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.zchao.blog.annotation.IgnoreToken;
import xyz.zchao.blog.pojo.Link;
import xyz.zchao.blog.service.LinkService;
import xyz.zchao.blog.util.PageResultVO;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

import javax.validation.Valid;
import java.util.List;

/**
 * @Description:
 * @Author: guozongchao
 * @Date: 2020/5/17 1:29
 */
@RestController
@RequestMapping("/link")
public class LinkController {
    @Autowired
    private LinkService linkService;

    @IgnoreToken
    @GetMapping("/list")
    public PageResultVO getLinks(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit) {
        List<Link> links = linkService.retrieveAllByPaging(page, limit);
        long count = linkService.getCount();
        return new PageResultVO(ResultCode.SUCCESS, links, count);
    }

    @IgnoreToken
    @GetMapping("/list/{lid}")
    public ResultVO getLink(@PathVariable("lid") Integer lid) {
        Link link = linkService.retrieveById(lid);
        return new ResultVO(ResultCode.SUCCESS, link);
    }

    @PutMapping("/list/{lid}")
    public ResultVO updateLink(@PathVariable("lid") Integer lid, @RequestBody @Valid Link record) {
        record.setLinkId(lid);
        linkService.update(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @DeleteMapping("/list/{lid}")
    public ResultVO deleteLink(@PathVariable("lid") Integer lid) {
        linkService.deleteById(lid);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @PostMapping("/add")
    public ResultVO addLinks(@RequestBody @Valid Link record) {
        linkService.create(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }
}
